﻿using System.Collections.Generic;
using Com.OpenCode.Framework.Core;
using Com.OpenCode.Framework.DevForm;

namespace Com.OpenCode.Framework.Workbench
{
    /// <summary>
    ///     UI工作台插件激活器。
    /// </summary>
    public class WorkbenchActivator : IAddinActivator
    {
        private MainForm mainForm;
        private static ICondition Condition;

        public void Start(Addin addin)
        {
            OpenCodeSplashScreenManager.Show("正在启动...");
            for (int i = 0; i < AddinTree.Addins.Count; i++)
            {
                Addin currentAddin = AddinTree.Addins.Get(i);
                Plugin conditon = currentAddin.Plugin.Search("Condition");
                if (conditon != null)
                {
                    Condition = currentAddin.Bulid(conditon) as ICondition;
                }
            }
            WorkbenchPlugin workbenchPlugin = new WorkbenchPlugin(AddinTree.Addins);
            mainForm = addin.Bulid(workbenchPlugin.Plugin, null) as MainForm;
            mainForm.StartLoad += mainForm_StartLoad;
            OpenCodeSplashScreenManager.Close();
            mainForm.ShowDialog();
        }

        public void Stop(Addin addin)
        {
            if (mainForm != null)
            {
                mainForm.Close();
            }
        }

        /// <summary>
        /// 在创建之前检查条件。
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns></returns>
        public static bool CheckCondition(Plugin plugin)
        {
            if (plugin == null)
            {
                return false;
            }
            if (Condition != null)
            {
                return Condition.Validate(plugin.Properties.GetString("Class"));
            }
            else
            {
                return true;
            }
        }

        private void mainForm_StartLoad(MainForm form)
        {
            List<Plugin> docks = form.BuildItemEventArgs.Plugin.ToList(p => p.Name == "Dock");
            foreach (Plugin plugin in docks)
            {
                if (plugin.Properties.GetBool("AutoStart"))
                {
                    form.BuildItemEventArgs.Plugin.Addin.Bulid(plugin, form.DockManagerUI);
                }
            }
            if (docks.Count > 0)
            {
                mainForm.DockManagerUI.RefreshLayout();
            }
        }
    }
}